const Koa = require('koa')
const app = new Koa()
const views = require('koa-views') //模板引擎
const json = require('koa-json')
const onerror = require('koa-onerror') //错误插件
const bodyparser = require('koa-bodyparser') //包体解析
const logger = require('koa-logger')
// 子服务
const server = require('http').createServer(app.callback())
// 跨域
const cors = require('koa2-cors')
// 静态资源对象
const Resources = require('./global/resources').Resources();

// http路由
const index = require('./routes/index')
const users = require('./routes/users')
// socket 通讯
const socket = require('./socket/index').socket(server)
const port = 3038;

// socket服务监听端口
server.listen(process.env.PORT || port, () => {
     console.log(`app run at : http://127.0.0.1:${port}`);
})

// error handler
onerror(app)

// middlewares
// 处理跨域
// app.use(async (ctx, next) => {
//   ctx.set("Access-Control-Allow-Origin", "*")
//   await next()
// })
app.use(cors())
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  // console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
